package com.easy.auth.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.easy.auth.domain.FileComparator;
import com.easy.auth.domain.Report;
import com.easy.auth.service.ReportService;
import com.easy.base.service.impl.EManagerImpl;
import com.easy.common.jdbc.DymaticCondition;
import com.easy.common.jdbc.PageInfo;
import com.easy.common.util.BeanUtil;
import com.easy.common.util.DateUtil;
import com.easy.common.util.FileUtil;
import com.easy.common.util.Parameter;
import com.easy.common.util.SqlUtil;
import com.easy.common.web.PagedList;

@Transactional
@Service
public class ReportServiceImpl extends EManagerImpl<Report> implements ReportService {

	@Override
	public int removeReport(String oids) {
		int count = 0;
		String[] userIds = oids.split("-");
		String sql = "DELETE FROM report_role WHERE userid = ?";
		if (userIds != null) {
			for (String userid : userIds) {
				super.update(sql, userid);
				Report report = new Report();
				report.setOid(userid);
				count += super.remove(report);
			}
		}
		return count;
	}

	@Override
	public Report findReport(Report report) {
		return super.find(report);
	}

	@Override
	public PagedList<Report> findAllReportLike(Report report,
			PageInfo pageInfo) {
		return super.findAllLike(report, pageInfo);
	}
	
	@Override
	public List<Report> getSonReportTree(String id) {
//		String sql="SELECT * FROM Report WHERE 1=1  AND id_path LIKE '%,"+id+"' AND isfile != true";
//		List<Report> father= queryList(sql, null,new BeanPropertyRowMapper<Report>(Report.class)	);
		String sql="SELECT * FROM Report WHERE 1=1  AND id_path LIKE '%,"+id+",%'  AND  isfile != 'true'";
		List<Report> son= queryList(sql, null,new BeanPropertyRowMapper<Report>(Report.class)	);
//		father.addAll(son);
		return son;
	}
	public List<Report> getSonReport(String pid) {
		String sql="SELECT * FROM Report WHERE  pid = '"+pid+"' AND isfile != 'true'";
		List<Report> reportList= queryList(sql, null,new BeanPropertyRowMapper<Report>(Report.class)	);
		return reportList;
	}	
	
	@Override
	public PagedList<Report> findAllReportEqual(Report report,
			PageInfo pageInfo) {
		return super.findAllEqual(report, pageInfo);
	}
	
	
	@Override
	public PagedList<Report> findAllReportLikeAndEqualPid(Report report,PageInfo pageInfo) {
		String equal= " = ";
		if(report.getPid()==null||report.getPid().equals("0")){
			equal= " <> ";
		}
		String r ="pid "+equal+" '"+report.getPid()+"'";
		if(report.getPid()==null){
			r="";
		}
		String sql=SqlUtil.getSelectAllLikeValueSql(report).replace("pid LIKE '%"+report.getPid()+"%'",r );
		return query(sql, null,
				new BeanPropertyRowMapper<Report>(BeanUtil.getGenericType(this, 0)),
				pageInfo);
	}
	
	
	
	@Override
	public int saveOrEditReport(Report report) {
		return super.saveOrEdit(report);
	}

	public PagedList<Report> getDepHaveUsersByUserid(String depid,
			PageInfo pageInfo) {
		String sql = "SELECT user.* FROM report user, report_department userdept "
				+ "WHERE 1=1 and user.oid = userdept.userid ";
		DymaticCondition dymaticCondition = new DymaticCondition();
		dymaticCondition.addCondition("AND userdept.departmentid = '?'", depid);

		return super.query(
				sql,
				dymaticCondition,
				new BeanPropertyRowMapper<Report>(BeanUtil.getGenericType(this, 0)), pageInfo);
	}

	public PagedList<Report> getDepNotHaveUsersByUserId(String depid,
			PageInfo pageInfo) {
		String sql = "SELECT * FROM report WHERE 1= 1 ";
		DymaticCondition dymaticCondition = new DymaticCondition();
		dymaticCondition
				.addCondition(
						"AND oid NOT IN(SELECT user.oid FROM report user, report_department userDept WHERE userDept.userid = user.oid and userDept.departmentid = '?')",
						depid);

		return super.query(
				sql,
				dymaticCondition,
				new BeanPropertyRowMapper<Report>(BeanUtil.getGenericType(this, 0)), pageInfo);
	}
	@Override
	public int removeAllReports() {
		String sql = "DELETE FROM report";
		super.update(sql);
		return 0;
	}

	public int addDepartmentUsers(String depid, String[] userids) {
		int count = 0;
		if (userids != null) {
			for (String userid : userids) {
				String sql = "INSERT INTO report_department VALUES(?, ?)";
				count += super.update(sql, userid, depid);
			}
		}
		return count;
	}
	
	public int  updateisroot() {
				String sql = "	UPDATE `report` SET isroot ='true' WHERE id IN(			"
						+ "SELECT pid FROM (SELECT * FROM `report` ) AS b WHERE isfile ='true'	"
						+ ")";
				 super.update(sql);
		return 0;
	}

	
	
	@Override
	public List<Report> findAllReports() {
		String sql="SELECT * FROM Report WHERE isfile != 'true'";
		List<Report> reportList= queryList(sql, null,new BeanPropertyRowMapper<Report>(Report.class)	);
		return reportList;
	}
	
//	@Override
	public List<Report> findAllList() {
		return super.findList(new Report());
	}
	
	
	@Override
	public int  readNewFloderAndReport(String maxid){
		//List<Report> reportList=findAllList();
		 List<String> newDirectory=compartDataAndDirectory(Parameter.PID,Parameter.FILE_PATH);
		
		return 0;
	}
	/**
	 * 废弃
	 * @param pid
	 * @param filePath
	 * @return
	 */
	
	public List<String>  compartDataAndDirectory(String pid,String filePath){
		List<String> newDirectory=new LinkedList<String>();
		List<Report> reportList=getSonReport(pid);
		File file = new File(filePath);
		File[] fileList = listFilesFilter(file);
		if( fileList.length==reportList.size()){
			for (int j = 0; j < reportList.size(); j++) {
				compartDataAndDirectory(reportList.get(j).getId(),fileList[j].getPath());
			}
		}else{
			for (int i = 0; i < fileList.length; i++) {
				for (int j = 0; j < reportList.size(); j++) {
					if(!fileList[i].getName().equals(reportList.get(j).getNas_path())){
						newDirectory.add(fileList[i].getPath());
					}
				}
				fileList[i].getName();
			}
		}
		return newDirectory;
	}
	
	
	
	@Override
	public int  readAllFloderAndReport(String path) {
		//FileUtil.login();
		return readAllFloderAndReport(path,0,1);
	}
	
	public int  readAllFloderAndReport(String path,int id,int level){
		File file = new File(path);
		List<Report> reportList=new ArrayList<Report>();// 
		int number=readFile(reportList,file,id,level,id+"");
		int reportNo=0;
		for (Report report : reportList) {
			save(report);
			if(report.getIsfile()!=null&&report.getIsfile().equals("true")){
				reportNo++;
			}
		}
		return reportNo;
	}
	public int  readFile(List<Report> reportList,File directory,Integer pid,Integer level,String idPath) {
		File[] fileList = listFilesFilter(directory);
		//reportList
		level=level+1;		
		Integer id=pid+1;
		for (int i = 0; i < fileList.length; i++) {
			id=id+i;
			String next_id_path=idPath+","+id;
			String name=fileList[i].getName();
			String state="open";
			if(level<7){
				name=tranlate(name);
			}
			if(level==2){
				state=("closed");
			}
			Report report=new Report(id.toString(), pid.toString(), name, level.toString(), next_id_path+",", state, DateUtil.getSystemDate());

			if (fileList[i].isDirectory()) {
				if(fileList[i].getName().equals("HTMLFolder")){
					//继续读取但是不保存此文件夹
					id=readHTMLFolder(reportList,fileList[i],pid,level-1,idPath,fileList.length);
				}else{
					reportList.add(report);
					id=readFile(reportList,fileList[i],id,level,next_id_path);
				}
			}else if (fileList[i].isFile()) {
				// System.out.println(fileList[i].getPath()+"");
					//File a= new File(Parameter.LOCAL_PATH+"//"+report.getOname());
				String file_create_time=DateUtil.getDateStringByformat("yyyy-MM-dd",fileList[i].lastModified());
				String local_name=DateUtil.getDateStringByformat("yyyy-MM-dd-HH-mm-ss",fileList[i].lastModified())+"_"+report.getOname();
				report.setFile_create_time(file_create_time);
				//report.setIsroot("true");
				report.setIsfile("true");
				report.setNas_path(fileList[i].getPath());
				report.setLocal_name(local_name);
				report.setLocal_path(Parameter.LOCAL_PATH+"\\"+local_name);
				FileUtil.copyfileChannel(report.getNas_path(), Parameter.LOCAL_PATH+"\\"+local_name);
				reportList.add(report);
			}
			
		}
		return id;
		
	}

	public int  readHTMLFolder(List<Report> reportList,File directory,Integer pid,Integer level,String idPath,int number) {
		File[] HTMLFolderList = listFilesFilter(directory);
		if(HTMLFolderList.length==1&&HTMLFolderList[0].getName().equals("OnDemand")){
			
		}else {
			System.err.println("readHTMLFolder ERROR:"+directory.getPath());
		}
		File[] OnDemandFileList = listFilesFilter(HTMLFolderList[0]);
		int id = pid +number;
		for (int i = 0; i < OnDemandFileList.length; i++) {
			File[] ReportfileList = listFilesFilter(OnDemandFileList[i]);
			if(ReportfileList.length!=1){
				System.err.println("readOnDemandFileList ERROR NOT ONLY ONE:"+OnDemandFileList[i].getPath());
				continue;
			}
			id = id +i;
			String id_path=idPath+","+id;
			String name=ReportfileList[0].getName();
			String state="open";
			Report report=new Report(id+"", pid.toString(), name, level.toString(), id_path, state, DateUtil.getSystemDate());

		  if (ReportfileList[0].isFile()) {
				// System.out.println(fileList[i].getPath()+"");
					//File a= new File(Parameter.LOCAL_PATH+"//"+report.getOname());
				String file_create_time=DateUtil.getDateStringByformat("yyyy-MM-dd",ReportfileList[0].lastModified());
				report.setFile_create_time(file_create_time);
				//report.setIsroot("true");
				report.setIsfile("true");
				report.setNas_path(ReportfileList[0].getPath());
				String local_name=file_create_time+"_"+report.getOname();
				report.setLocal_name(local_name);
				report.setLocal_path(Parameter.LOCAL_PATH+"\\"+local_name);
				FileUtil.copyfileChannel(report.getNas_path(), Parameter.LOCAL_PATH+"\\"+local_name);
				reportList.add(report);
			}else{
				System.err.println("readOnDemand's Report File List ERROR: NOT A FILE"+ReportfileList[0].getPath());
			}
			
		}
	return id;
	}
	
	
	public String tranlate(String name) {
		if (name.equals("Plant1")) {
			name = "一厂";
		} else if (name.equals("Plant2")) {
			name = "二厂";
		} else if (name.equals("Functional_Gage")) {
			name = "检具";
		} else if (name.equals("Waixie")) {
			name = "外协";
		} else if (name.equals("Zizhi")) {
			name = "自制";
		}
		return name;
	}
	
	  /**
	   * 过滤 并按照时间排序，时间越早越靠前
	   * @param file
	   * @return
	   */
	 public File[] listFilesFilter(File file) {
		 List<File> fileList=new LinkedList<File>();
		 File[] fileArray=file.listFiles();
		 Arrays.sort(fileArray, new FileComparator()); 
		 for (int i = 0; i < fileArray.length; i++) {
			if (fileArray[i].isDirectory()) {
				fileList.add(fileArray[i]);
				continue;
			}
			String fileName = fileArray[i].getName();
			String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
			if (prefix.toLowerCase().equals(Parameter.FILE_TYPE_PDF)) {
				fileList.add(fileArray[i]);
			}

		}
		return fileList.toArray(new File[fileList.size()]);
    }

//	 UPDATE `report` SET isroot ='true' WHERE id IN(
//			 SELECT pid FROM (SELECT * FROM `report` ) AS b WHERE isfile ='true'
//			 )

//	 UPDATE `report` SET iconcls ='icon-data' WHERE isfile <> 'true' AND isroot <> 'true'




}
